package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @author bairimengchang
 * @version 1.0
 * @project sky-take-out
 * @description 定时任务（处理超时订单状态更新、订单派送60分钟后订单状态更新）
 * @date 2024/9/8
 */
@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrdersMapper ordersMapper;

    // 每分钟执行一次
    public static final String CRON_EVERY_MINUTE = "0 0/1 * * * ?";

    // 处理超时订单（超时15分钟用户还未付款）状态更新
    @Scheduled(cron = CRON_EVERY_MINUTE)
    public void processTimeoutOrder() {

        log.info("处理超时订单开始，当前时间:{}", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));

        // 获取当前时间减去15分钟
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);

        // 查询数据库中所有下单时间早于这个时间的订单
        log.info("处理超时订单，早于该时间就会被取消订单:{}", time);

        // 订单状态是待付款，并且超时15分钟未支付
        List<Orders> ordersList = ordersMapper.selectStatusAndOrderTime(Orders.PENDING_PAYMENT, time);
        log.info("查询到{}个超时订单", ordersList.size());

        // 更新订单状态为已取消6
        // 取消原因是订单超时
        for (Orders orders : ordersList) {
            orders.setStatus(Orders.CANCELLED);
            orders.setCancelReason("订单超时，系统自动取消");
            orders.setCancelTime(LocalDateTime.now());
            ordersMapper.updateByPrimaryKeySelective(orders);
            log.info("更新订单状态为已取消，订单id为:{}", orders.getId());
        }

    }


}
